<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot-scope="{}" slot="serviceNoSearch">
        <select-page ref="searchSerSelect" label="serviceName" value="serviceNo" :select.sync="searchForm.serviceNo" :url="website.searchLink.serviceUrl" placeholder-text="服务商" filter-key="searchParam"></select-page>
      </template>
      <template slot="menuLeft">
        <!-- <el-button type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.user_wallet_delete"
          @click="handleDelete">删 除
        </el-button> -->
        <!-- <el-button
          type="primary"
          size="small"
          icon="el-icon-delete"
          @click="beforeYuEQK"
          >余额清空
        </el-button>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-sort"
          @click="beforeYuEHz"
          >余额划转
        </el-button> -->
      </template>
      <template slot="menuRight">
        <!-- <el-button type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.user_wallet_import"
          @click="handleImport">导入
        </el-button> -->
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permissionList.exportBtn"
          @click="handleExport"
          >导出
        </el-button>
      </template>
    </avue-crud>
    
    <div class="curd-foter">
      <div class="redFontBox">总余额：<span class="redFont">{{ exhibition(countData.totalBalance) || 0}}</span> 元</div>
      <div class="redFontBox">总应收：<span class="redFont">{{ exhibition(countData.totalReceivable ) || 0 }}</span> 元</div>
      <div class="redFontBox">总应付：<span class="redFont">{{ exhibition(countData.totalPayable) || 0 }}</span> 元</div>
      <div class="redFontBox">总发票额度：<span class="redFont">{{ exhibition(countData.totalInvoiceLimit) || 0 }}</span> 元</div>
      <div class="redFontBox">总提现中：<span class="redFont">{{ exhibition(countData.totalBalancing) || 0 }}</span> 元</div>
      <div class="redFontBox">总待确认分润：<span class="redFont">{{ exhibition(countData.totalConfirmProfit) || 0 }}</span> 元</div>
    </div>


    <!-- 余额清空 -->
    <el-dialog title="余额清空"  v-loading="showEmptyLoading" :visible.sync="showEmpty" v-if="showEmpty"  width="600px" :close-on-click-modal="false" append-to-body>
      <div style="position: relative;height: 50px;">
        <el-button  type="primary" @click="emptyBoxExel = true" size="small" style="position: absolute;right: 0;">批量导入</el-button>
      </div>
      <avue-form ref="emptyForm" :option="optionEmpty" v-model="emptyForm" ></avue-form>

      <el-dialog title="数据导入"
        append-to-body
        :visible.sync="emptyBoxExel"
        top="20vh"
        width="555px"
        >
        <avue-form :option="emptyOptionExel"
          v-model="emptyBoxExelForm"
          :upload-after="uploadAfterEmpty">
          <template slot="excelTemplate">
            <el-button type="primary" @click="dowEmpty">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" v-preventClick @click="emptySubmit">提 交</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="showEmpty = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 余额划转 -->
    <el-dialog title="余额划转" v-loading="showConversionLoading" :visible.sync="showConversion" v-if="showConversion"  width="600px" :close-on-click-modal="false" append-to-body>
      <div style="position: relative;height: 50px;">
        <el-button  type="primary" @click="conversionBoxExel = true" size="small" style="position: absolute;right: 0;">批量导入</el-button>
      </div>
      <avue-form ref="conversionForm" :option="optionConversion" v-model="conversionForm"></avue-form>

      <el-dialog title="数据导入"
        append-to-body
        :visible.sync="conversionBoxExel"
        top="20vh"
        width="555px"
        >
        <avue-form :option="conversionOptionExel"
          v-model="conversionBoxExelForm"
          :upload-after="uploadAfterConversion">
          <template slot="excelTemplate">
            <el-button type="primary" @click="dowConversion">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" v-preventClick @click="conversionSubmit">提 交</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="showConversion = false">取 消</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  balanceRecordChange,
  getExport,
  getListCount
} from "@/api/rb-service/wallet/user_wallet";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import { downloadFileExcel } from "@/util/util";

export default {
  data() {
    var validateSwitchNo = (rule, value, callback)=>  {
      if (value === '') {
        callback(new Error('请选择转入用户编号！'));
      } else if (value == this.conversionForm.userNo) {
        callback(new Error('转出转入用户编号不能一样！'));
      } else {
        callback();
      }
    };
    var validateSwitchNo1 = (rule, value, callback)=>  {
      if (value === '') {
        callback(new Error('请选择转出用户编号！'));
      } else if (value == this.conversionForm.switchNo) {
        callback(new Error('转出转入用户编号不能一样！'));
      } else {
        callback();
      }
    };
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        // height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        viewBtn: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        labelWidth: 100, //弹出表单的标题的统一宽度
        searchLabelWidth: 100, //搜索框标题宽度
        menuWidth: 100, //操作栏宽度
        menu:false,
        column: [
          {
            label: "服务商编号",
            searchLabel: "服务商",
            prop: "serviceNo",
            type: "input",
            sortable: true,
            search: true,
            overHidden: true,
          },
          {
            label: "服务商名称",
            prop: "serviceName",
            type: "input",
            overHidden: true,
          },
          {
            label: '',
            prop: 'isSelectChild',
            type: 'select',
            multiple: false,
            dataType: "string",
            showColumn: false,
            hide: true,
            search: true,
            searchType:"checkbox",
            searchSpan:2,
            searchLabelWidth: '0',
            dicData: [{
              label:'包含下级',
              value: 1
            }]
          },
          // {
          //   label: '',
          //   prop: 'isSelectDirect',
          //   type: 'select',
          //   multiple: false,
          //   dataType: "string",
          //   showColumn: false,
          //   hide: true,
          //   search: true,
          //   searchType:"checkbox",
          //   searchSpan: 2,
          //   searchLabelWidth: '0',
          //   dicData: [{
          //     label:'直属服务商',
          //     value: 1
          //   }]
          // },
          {
            label: "余额",
            prop: "balance",
            type: "input",
            overHidden:true,
          },
          {
            label: "应收",
            prop: "receivable",
            type: "input",
            overHidden:true,
          },
          {
            label: "应付",
            prop: "payable",
            type: "input",
            overHidden:true,
          },
          {
            label: "发票额度",
            prop: "invoiceLimit",
            type: "input",
            overHidden:true,
          },
          {
            label: "提现中",
            prop: "balancing",
            type: "input",
            overHidden:true,
          },
          {
            label: "待确认分润",
            prop: "confirmProfit",
            type: "input",
            overHidden:true,
          },
        ],
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-service/service/wallet/user_wallet/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      // 余额清空
      showEmpty: false,
      emptyForm:{},
      optionEmpty:{
        menuSpan:24,
        labelWidth:120,
        submitBtn:false,
        emptyBtn:false,
        column: [
          {
            label: '用户编号',
            span: 18,
            type: "select",
            prop: "userNo",
            sortable: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请选择用户编号",
                trigger: "blur",
              },
            ],
            // dicData: [],
            props: {
              label: 'serviceName',
              value: 'userNo'
            },
            dicUrl:`/api/rb-service/service/serviceinfo/service_info/list?current=-1&size=-1&serviceAuditStatus=2`,
            dicFormatter:(data)=>{
              return data.data.records
            },
            filterable: true,
          }
        ]
      },
      emptyBoxExel: false,
      emptyBoxExelForm:{},
      emptyOptionExel: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-service/service/balancerecord/balance_record/importBlank",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      // 余额划转
      showConversion:false,
      conversionForm:{},
      optionConversion:{
        menuSpan:24,
        submitBtn:false,
        emptyBtn:false,
        labelWidth:120,
        column: [
          {
            label: '转出用户编号',
            span: 18,
            type: "select",
            prop: "userNo",
            sortable: true,
            search: true,
            rules: [{ required: true,validator: validateSwitchNo1, trigger: 'change' }],
            dicData: [],
            props: {
              label: 'serviceName',
              value: 'userNo'
            },
            dicUrl:`/api/rb-service/service/serviceinfo/service_info/list?current=-1&size=-1&serviceAuditStatus=2`,
            dicFormatter:(data)=>{
              return data.data.records
            },
            filterable: true,
          },
          {
            label: '转入用户编号',
            span: 18,
            type: "select",
            prop: "switchNo",
            sortable: true,
            search: true,
            rules: [{ required: true,validator: validateSwitchNo, trigger: 'change' }],
            dicData: [],
            props: {
              label: 'serviceName',
              value: 'userNo'
            },
            dicUrl:`/api/rb-service/service/serviceinfo/service_info/list?current=-1&size=-1&serviceAuditStatus=2`,
            dicFormatter:(data)=>{
              return data.data.records
            },
            filterable: true,
          }
        ]
      },
      conversionBoxExel: false,
      conversionBoxExelForm: false,
      conversionOptionExel: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-service/service/balancerecord/balance_record/importRecord",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ]
      },
      userNoTypelist:[],//用户编号
      showEmptyLoading:false,
      showConversionLoading:false,
      countData: {},
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.service_wallet_view, false),
        exportBtn: this.vaildData(this.permission.service_wallet_export, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == "-1") {
          return (val = 0);
        } else {
          return val;
        }
      };
    }
  },
  methods: {
    // 余额清空 --- 提交
    emptySubmit(){
      this.$refs.emptyForm.validate((vaild,done)=>{
          if(vaild){
            this.showEmptyLoading=true;
            this.emptyForm.changeType='0';
            balanceRecordChange(this.emptyForm).then(() => {
              this.$refs.emptyForm.resetForm();
              done()
              this.$message.success("操作成功!");
              this.showEmptyLoading=false;
              this.showEmpty=false;
            }).catch(() =>{
              done()
              this.showEmptyLoading=false;
            })
          }
        })
    },
    // 余额清空 ---下载模板
     dowEmpty() {
      window.open(
        `/api/rb-service/service/balancerecord/balance_record/blankTemplate?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    // 余额清空 ---上传之后的回调
    uploadAfterEmpty(res, done) {
      this.emptyBoxExel = false;
      this.showEmpty=false;
      this.showEmptyLoading=false;

      done();
    },
    beforeYuEQK(){
      this.showEmpty = true ;
      this.emptyForm = {};
    },
    beforeYuEHz(){
      this.showConversion = true;
      this.conversionForm = {};
    },
    // 余额划转 --- 提交
    conversionSubmit(){
      this.$refs.conversionForm.validate((vaild,done)=>{
          if(vaild){
            this.showConversionLoading=true;
            this.conversionForm.changeType='1';
            balanceRecordChange(this.conversionForm).then(() => {
              this.$refs.conversionForm.resetForm();
              done()
              this.conversionForm={};
              this.$message.success("操作成功!");
              this.showConversionLoading=false;
              this.showConversion=false;
            }).catch(() =>{
              done()
              this.showConversionLoading=false;
            })
          }
        })
    },
    // 余额划转 ---下载模板
    dowConversion() {
      window.open(
        `/api/rb-service/service/balancerecord/balance_record/recordTemplate?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    // 余额划转 ---上传之后的回调
    uploadAfterConversion(res, done) {
      this.conversionBoxExel = false;
      this.showConversion=false;
      this.showConversionLoading=false;
      done();
    },

    /**
     *
        rowSave(row, done, loading) {
          add(row).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              done();
            },
            (error) => {
              loading();
              window.console.log(error);
            }
          );
        },
        rowUpdate(row, index, done, loading) {
          update(row).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              done();
            },
            (error) => {
              loading();
              window.console.log(error);
            }
          );
        },
        rowDel(row) {
          this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              return remove(row.id);
            })
            .then(() => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!",
              });
            });
        },
        handleDelete() {
          if (this.selectionList.length === 0) {
            this.$message.warning("请选择至少一条数据");
            return;
          }
          this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              return remove(this.ids);
            })
            .then(() => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.$refs.crud.toggleSelection();
            });
        },
     */

    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.userType = 2;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });

      // 获取统计
      getListCount(Object.assign(params, this.query)).then((res) => {
        this.countData = res.data.data;
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      // let exQuery = ``;
      // exQuery += `&userNo=${this.search.userNo}`;
      // exQuery += `&userName=${this.search.userName}`;


      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // window.open(
        //   `/api/rb-service/service/wallet/user_wallet/export?${
        //     this.website.tokenHeader
        //   }=${getToken()}` + exQuery
        // );
        getExport(this.search).then((res) => {
          downloadFileExcel(res);
        },(error) => {
            window.console.log(error);
          }
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-service/service/wallet/user_wallet/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  }
};
</script>

<style lang="scss" scoped>
.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;

  .redFontBox {
    margin-right: 40px;
    .redFont {
      color: red;
    }
  }
}
</style>
